import preferences from '@ohos.data.preferences'
import { Constants } from './Constants'

class PreferenceUtil {
  private pref: preferences.Preferences

  async initPreference(context) {
    try {
      this.pref = await preferences.getPreferences(context, Constants.STORE_NAME)
      console.log(`加载${Constants.STORE_NAME}成功`)
    } catch (e) {
      console.log(`加载${Constants.STORE_NAME}失败`, JSON.stringify(e))
    }
  }

  async  putPerfValue(key: string, value: preferences.ValueType) {
    if (!this.pref) {
      console.log(`preference[${Constants.STORE_NAME}]尚未初始化！`);
      return
    }

    try {
      await this.pref.put(key, value)
      await this.pref.flush()

      console.log(`保存preference[${key} : ${value}]成功`)
    } catch (e) {
      console.log(`保存preference[${key} : ${value}]失败`, JSON.stringify(e))
    }
  }

  async getPrefValue(key: string, defaultValue: preferences.ValueType) {
    if (!this.pref) {
      console.log(`preference[${Constants.STORE_NAME}]尚未初始化！`);
      return
    }

    try {
      let value = await this.pref.get(key, defaultValue)
      console.log(`读取preference[${key} : ${value}]成功`)
      return value
    } catch (e) {
      console.log(`读取preference[${key}]失败`, JSON.stringify(e))
    }
  }
}

const preferencesUtil = new PreferenceUtil()

export default preferencesUtil as PreferenceUtil

//export const PreferenceUtil = new PreferenceUtil()